/**
 * Created by weng on 2018/1/16.
 */
var uuid = require("node-uuid");
const sea = require('../common/sea');
const request = require('../common/Request');
const RequestPost = request.RequestPost
const RequestPosturlencoded = request.RequestPosturlencoded
const RequestPostFom = request.RequestPostFom
const RequestGet = request.RequestGet
const sqlOrm = require('../common/sqlModel');
const apiClient = require('../lib/api/topClient.js').TopClient;
const utils = require("../common/utils")
const config = require("../common/config")
// const sea = require("../common/sea")

const ItemType__ITEM_TYPE_BEGIN      = 0
const ItemType__ITEM_RED_CRYSTAL     = 600001
const ItemType__ITEM_BLUE_CRYSTAL    = 600002
const ItemType__ITEM_GOD_GOOD        = 600003
const ItemType__ITEM_RECRUIT_TICKET  = 600004


const fs = require('fs');
const  path = require("path")

var cache = require('memory-cache');

class Csfs {

    async login(req, res, body, cb) {
        try {
            let {userName,password} = body
            let UserInfo = await sqlOrm.paccount.findAsync({account:userName,passWd:password});
            if(UserInfo.length <= 0){
                return cb({code:500,msg:"账号密码错误",status: 'error'})
            }
            let id = UserInfo[0].id
            let session = uuid.v4().substring(0,31);
            cache.put("id_"+id,cache)
            console.log("keys ",cache.keys())
            let currentAuthority = "guest"

                switch (UserInfo[0].power){
                    case '1':
                        currentAuthority = "admin"
                        break
                    case '2':
                        currentAuthority = "user"
                        break
                }
                let name = UserInfo[0].account
            return cb({code:200,session,id,status:"ok",currentAuthority,name})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e, status: 'error',})
        }
    }

    async loginOut(req, res, body, cb) {
        try {
            let {id} = body
            cache.del ("id_"+id)
            console.log("keys ",cache.keys())
            return cb({code:200})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    async updatePwd(req, res, body, cb) {
        try {
            let {id,newPasswd} = body
            let pAccount = await sqlOrm.paccount.findAsync({id})
            pAccount[0].passWd =newPasswd
            await pAccount[0].saveAsync()

            return cb({code:200})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 玩家账号查询
    async AccountList(req, res, body, cb) {
        try {
            let {account} = body;
            let UserInfo = await sqlOrm.account.findAsync({account});
            if(account.length <= 0){
                return cb({code:500,msg:"没有账号信息"});
            }

            let info = UserInfo[0];
            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }


    // 玩家账号查询
    async currentUse(req, res, body, cb) {
        try {
            let {id} = body;
            let currentUser = await sqlOrm.paccount.findAsync({id})
            if(currentUser.length > 0){
                currentUser = currentUser[0]
            }
            return cb(currentUser)
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 报表数据查询
    async TableInfo(req, res, body, cb) {
        try {
            let {account,startTime,endTime} = body;

            startTime =await utils.FormMatDate(startTime)
            endTime = await utils.FormMatDate(endTime)
            console.log("endTime",endTime)
            console.log("startTime",startTime)
            let sharesumMayPayEd = await sqlOrm.connectionLocalhot.execQueryAsync("call table_mc(?,?)", [startTime,endTime])
            console.log("sharesumMayPayEd",sharesumMayPayEd)
            let trade_mc = sharesumMayPayEd[0];
            let dayNum = 0;
            let allUser = 0;
            if(sharesumMayPayEd[1].length > 0){
                 dayNum = sharesumMayPayEd[1][0].dayNum
                 allUser = sharesumMayPayEd[1][0].allNum
            }


            let activeNum = 0
            if(sharesumMayPayEd[2].length > 0){
                activeNum = sharesumMayPayEd[2][0].value
            }
            let yangren = 0
            if(sharesumMayPayEd[3].length > 0){
                yangren =  sharesumMayPayEd[3][0].value
            }
            let upYangren = 0
            if(sharesumMayPayEd[4].length > 0){
                upYangren = sharesumMayPayEd[4][0].value
            }
            let yesterCc = 0
            if(sharesumMayPayEd[5].length > 0){
                yesterCc = sharesumMayPayEd[5][0].value
            }

            // let yangren = sharesumMayPayEd[3][0].value
            // let upYangren = sharesumMayPayEd[4][0].value


            let offlineChartData = []
            let offlineData = []
            const msgs = [ '每日交易'];
            for (let i = 0; i < msgs.length; i += 1) {
                offlineData.push({
                    name: `${msgs[i]}`,
                });
            }
            offlineChartData[0] = []
            for(var tradeInfo of trade_mc){
                offlineChartData[0].push(
                    {
                        x:new Date(tradeInfo.time).getTime(),
                        y1:tradeInfo.value
                    }
                )
            }

            let yestInfo = [allUser,dayNum,activeNum,yesterCc,yangren,upYangren]
            return cb({code:200,offlineChartData :offlineChartData ,offlineData,yestInfo})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }


    // 查询平台账号
    async getPaccount(req, res, body, cb) {
        try {
            let {account,passWd,ban,id} = body;
            let info = await sqlOrm.paccount.findAsync({})
            if(info.length <= 0 ){
                return cb({code:500,msg:"owner account is not exit"})
            }

            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 添加平台账号
    async addPaccount(req, res, body, cb) {
        try {
            let {account,passwd,userId} = body;
            let ownerInfo = await sqlOrm.paccount.findAsync({id:userId})
            if(ownerInfo <= 0 ){
                return cb({code:500,msg:"owner account is not exit"})
            }

            await sqlOrm.paccount.createAsync({account,passWd:passwd,owner:ownerInfo[0].account,power:2,createTime:util.FormMatTime(new Date())})
            let info = await sqlOrm.paccount.findAsync({})
            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 警告信息
    async traceWarn(req, res, body, cb) {
        try {
            console.log("traceWarn body is : ",body)
            let info = []
            let {time, warnFlag} = body
            if(warnFlag == 0){
                info =  await  sqlOrm.connectionLocalhot.execQueryAsync("SELECT *, item_value as itemValue from attribute_log where  DATE_FORMAT(time,'%Y-%m-%d') = ? order by time desc ",[time]);
            }else{
                info =  await  sqlOrm.connectionLocalhot.execQueryAsync("SELECT *, item_value as itemValue from attribute_log where rate/type > 5.3 and  DATE_FORMAT(time,'%Y-%m-%d') = ? order by time desc ",[time]);
            }

            //info =  await sqlOrm.AttributeLog.findAsync({time})

            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }
    // 拥有英雄等级
    async getHeroNum(req, res, body, cb) {
        try {
             console.log("body is :",body)
            let info = []
            let {time} = body
            console.log("time is :",time)
            time = utils.FormMatDate(time)
            let heroType = await sqlOrm.hero_Num.findAsync({time});

            for(var hero of heroType){
                info.push({
                    x:hero.hero_name,
                    y:hero.value_all
                })
            }
            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 基本信息
    async accountInfo(req, res, body, cb) {
        try {

            let {nick,ban,id,uuid} = body
            console.log("id:",id)
            console.log("uuid:",uuid)
            let  userInfo,currentUser
            if (nick && !id){
                userInfo = await sqlOrm.account.findAsync({nick})
                if (userInfo.length > 0){
                    id = userInfo[0].uuid
                }
            }
            console.log("dddddddddddd",id)
            if (id){
                uuid = id
            }
            if (uuid){
                var userinfo = await sqlOrm.account.findAsync({uuid})
            }

            if(userinfo.length <= 0){
                return cb({code:500})
            }
            let id_ = userinfo[0].id;
            let callInfo = await sqlOrm.connectionLocalhot.execQueryAsync("call UserInfo(?)", [id_])
            let UserInfo= callInfo[0];
            console.log("callInfo[1]",callInfo[1])
            let masterId = 0;
            let masterName = 0
            if(callInfo[1].length > 0){
                masterId = callInfo[1][0].id;
                masterName = callInfo[1][0].nick;
            }
            let num = 0
            if( callInfo[2].length > 0 ){
                num = callInfo[2][0].num;
            }
            let power = 0;
            if(callInfo[3].length > 0){
                power= callInfo[3][0].power;
            }

            let lv = 0;
            if(callInfo[4].length > 0){
                lv = callInfo[4][0].lv;
            }

            if(UserInfo.length <= 0){
                return cb({code:500,msg:"没有账号信息"});
            }

            currentUser = UserInfo[0];
            currentUser.masterId = masterId;
            currentUser.masterNick = masterName;
            currentUser.num = num;
            currentUser.power = power;
            currentUser.lv = lv;
            currentUser.ban = currentUser.status;
            let msg = {
                ulUserId : JSON.parse(currentUser.id)
            }

            try{
                request.wsClient(20005,msg, async function (res) {
                    console.log("333333",res)
                    if(res.code == 200){
                        // if(res.info == 1){
                            UserInfo = res.UserInfo;
                            currentUser.red_crystal = UserInfo.unRedCrystal/1000
                            currentUser.blue_crystal = UserInfo.unBlueCrystal/1000
                            currentUser.feats = UserInfo.unFeats/1000
                            currentUser.lv = UserInfo.heroes.length;
                            currentUser.ban = UserInfo.unStatus;
                        // }
                    }
                    console.log("返回1")
                    return cb({code:200,info:[currentUser]})
                })
            }catch(e){
                console.log("返回2")
                currentUser.red_crystal = currentUser.red_crystal/1000
                currentUser.blue_crystal = currentUser.blue_crystal/1000
                currentUser.feats = currentUser.feats/1000
                return cb({code:200,info:[currentUser]})
            }

        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    // 修改玩家属性
    async upateAccountInfo(req, res, body, cb) {
        try {
            let {ban,id} = body
            let  userInfo
           if(id){
                userInfo = await sqlOrm.account.findAsync({id})
            }

            if(userInfo && userInfo.length  <= 0 ){
                return cb({code:500,msg:"owner account is not exit"})
            }
            let msg = {
                  ulUserId  : body.id,
                  unStatus  :ban,
            }
            request.wsClient(20002,msg, async function (res) {
                console.log("333333",res)
                if(res.code == 200){
                    if(res.info == 2){
                        // 修改玩家状态
                        console.log("修改玩家状态",userInfo[0],ban)
                        userInfo[0].status = ban
                        await userInfo[0].saveAsync()
                    }
                    return cb({code:200,info:[]})
                }else {
                    // 修改玩家状态
                    console.log("修改玩家状态",userInfo[0],ban)
                    userInfo[0].status = ban
                    await userInfo[0].saveAsync()

                    return cb({code:200,info:[]})
                }
                })
            //let callInfo = await sqlOrm.connectionLocalhot.execQueryAsync("call UserInfo(?)", [id])
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }
    //
    async unDotrace(req, res, body, cb) {
        try {
            let {time,current} = body
            console.log("ddd",current,!current)
            if (!current){
                current = 1
            }else{
                console.log("xxxx",current)
            if( current ==  '0'){
                current =  1
            }
                current =  JSON.parse(current)
            }
            console.log("current",current)
            let startPage = (current -1 ) * 10;
            let pageEnd = startPage + 10;
            let info = {};
            console.log("startPage",startPage)
            console.log("pageEnd",pageEnd)
            let count = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT COUNT(*) total from trade");
            let list = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT t1.id,t2.uuid nick,t1.status,t1.trade_time,t1.seller_id,t1.buyer_id,t1.buyer_name,t1.item_type,t1.item_num FROM  trade t1,account t2 WHERE t1.seller_id = t2.id  limit ?,?",[startPage,10] );

            console.log("list",list[0])
            let total = count[0].total;
            info.list = list;
            info.pagination = {total:total,pageSize:10,current:current};
            return cb({code:200,info:info})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }
    //
    async updateTraceStatus(req, res, body, cb) {
        try {
            let {current,id,status} = body
            console.log("id ",id );
            console.log("status ",status );
            console.log("current",current,!current);
            if (!current){
                current = 1
            }else{
                if( current ==  '0'){
                    current =  1
                }
                current =  JSON.parse(current)
            }
            let tradInfo = await sqlOrm.trade.findAsync({id:id});

            if(tradInfo.length <= 0){
                return cb({code: 500, msg: "没有订单信息"})
            }

            let ulItemType = tradInfo[0].item_type;
            let ulItemNum = tradInfo[0].item_num;

            // 5:退货给买家 6：退货给卖家
            let ulUserId
            if(status == 5){
                ulUserId = tradInfo[0].buyer_id
                ulItemNum = ulItemNum * 0.8
            }else if(status == 6) {
                ulUserId = tradInfo[0].seller_id
            }

            let msg = {
              unTradeId :id,
              unStatue   :JSON.parse(status),
              ulUserId   :ulUserId,
              ulItemType  :ulItemType,
              ulItemNum   :ulItemNum,
            };
            let info = {};
            request.wsClient(20003,msg, async function (res) {
                console.log("333333",res)
                let accountInfo = await sqlOrm.account.findAsync({id:ulUserId});
                if(res.code === 200 && res.info === 1){
                    console.log("玩家在线修改完成")
                }else{
                    console.log("accountInfo.length ",accountInfo.length )
                    if(accountInfo.length > 0){
                        console.log("ulItemType.ulItemType ",ulItemType)
                        if(ulItemType === ItemType__ITEM_RED_CRYSTAL){
                            accountInfo[0].red_crystal +=ulItemNum
                        }else if(ulItemType === ItemType__ITEM_BLUE_CRYSTAL){
                            accountInfo[0].blue_crystal +=ulItemNum
                        }
                        accountInfo[0].saveAsync();
                    }
                }
                //  修改订单状态
                if(tradInfo.length > 0){
                    tradInfo[0].status = status
                    await tradInfo[0].saveAsync();
                }

                let startPage = (current -1 ) * 10;
                let pageEnd = startPage + 10;

                console.log("startPage",startPage)
                console.log("pageEnd",pageEnd)

                let count = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT COUNT(*) total from trade");
                let list = await sqlOrm.connectionLocalhot.execQueryAsync("SELECT t1.id,t2.nick,t1.status,t1.trade_time,t1.seller_id,t1.buyer_id,t1.buyer_name,t1.item_type,t1.item_num FROM  trade t1,account t2 WHERE t1.seller_id = t2.id  limit ?,?",[startPage,pageEnd] );
                // let list = await sqlOrm.connectionLocalhot.execQueryAsync("call TradeInfo(?,?)", [startPage,pageEnd]);
                // console.log("list",list[0])
                let total = count[0].total;
                info.list = list;
                info.pagination = {total:total,pageSize:10,current:current};
                return cb({code:200,info:info})
            })

        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }
    //
    async getTicketStatus(req, res, body, cb) {
        try {

            return cb({code:200,info:1})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }
    //
    async updateTicketStatus(req, res, body, cb) {
        try {
            let status = body.status;
            return cb({code:200,info:status})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    //
    async sendItem(req, res, body, cb) {
        try {
            console.log("wsClient",body)
            let msg = {
                  ulUserId  : JSON.parse(body.id),
                  ulItemId  :   JSON.parse(body.ItemId),
                  unItemNum  :   JSON.parse(body.Num),
            }

            request.wsClient(20001,msg, async function (res) {
                console.log("333333",res)
                if(res.code == 200){
                    if(res.info == 2){
                        let accountInfo = await sqlOrm.account.findAsync({id:body.id})
                        if (accountInfo.length > 0){
                            switch (body.ItemId){
                                case "0" :
                                    accountInfo[0].red_crystal += JSON.parse(body.Num);
                                    console.log("红水晶")
                                    break;
                                case "1":
                                    accountInfo[0].blue_crystal += JSON.parse(body.Num);
                                    console.log("蓝水晶")
                                case "2":
                                    accountInfo[0].ticket += JSON.parse(body.Num);
                                    console.log("收徒券")
                                    break;
                            }
                            await accountInfo[0].saveAsync();
                        }else{
                            return cb({code:500})
                        }
                    }
                }
                return cb({code:200})
            })

        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    async submitmaxValue(req, res, body, cb) {
        try {
            console.log("submitmaxValue body is:",body)
            let value = body.maxValue;
            return cb({code:200,info:value})
        } catch (e) {
            if (!e) e = 10 * "err"
            return cb({code: 500, msg: e})
        }
    }

    async sendMsg(req, res, body, cb) {
        try {
            console.log("sendMsg body is:",body)
            let phone = body.phone;
            if(phone.length > 11){
                return cb({code:500,msg:"号码格式不对"})
            }
            let accountSid = "373582b479f347b79c767d727c8cd7bc"
            let token = "6bf7e7a4206841aabd15039dc358a658"
            let  templateid = 1139745506
            let value = utils.getrandomNumber(6).info
            let param = value+ ",30"
            let to = phone;
            let timestamp  = utils.FormMatTimeNum(new Date().getTime())
            let sig = sea.getMd5Nomal(accountSid+token+timestamp)   // 签名。MD5(ACCOUNT SID + AUTH TOKEN + timestamp)。共32位（小写）。
            sig = sig.toLowerCase();
            let form = {
                accountSid,
                templateid,
                param,
                to,
                timestamp,
                sig
            }
            console.log("form :",form)
            let url = 'https://api.miaodiyun.com/20150822/industrySMS/sendSMS';
            console.log("url is",url)
            let res = await RequestPosturlencoded(url,form)
            console.log("res is",res)
            res = utils.toObjecty(res)
            if(res.respCode != "00000"){
                return cb({code:500,msg:"短信发送失败"})
            }
            console.log("res is",res)
            let lastPhone = await sqlOrm.phone_code.findAsync({
                phone
            });
            if(lastPhone.length > 0){
                lastPhone[0].remove();
            }

            let phoneInfo = await sqlOrm.phone_code.createAsync({
                phone,
                value:value
            })

            setTimeout(function () {
                phoneInfo.remove()
            },30 *  60 * 1000);

            return cb({code:200})
        } catch (e) {
             console.error("短信发送错误",e)
            return cb({code: 500, msg: "短信发送错误"})
        }
    }
}


async function GetClientIp (req) {
    var ip = req.headers['x-real-ip'] ||
        req.headers['x-forwarded-for'] ||
        req.socket.remoteAddress || '';
    if(ip.split(',').length>0){
        ip = ip.split(',')[0];
    }
    return ip;
};



module.exports = new Csfs();


